<script lang="ts" setup>
import { reactive, ref } from 'vue'
import { ConfigService } from '@/services/api/sys/config.service'
import { useRequest } from 'vue-request'
import EditForm from './EditForm.vue'
import type { IFormDialogTypeProps } from '@/components/sofastui/AdvancedForm/interface'

// Types
type OptionItem = { label: string; value: number }
type ConfigItem = {
  id: number
  title: string
  prop: string
  type?: number
  valueType?: string
  [key: string]: unknown
}
type EditFormRef = InstanceType<typeof EditForm> & {
  show: (type: IFormDialogTypeProps, data: ConfigItem, options: ConfigItem[]) => void
}

// Constants
const OPTIONS: OptionItem[] = [
  { label: '业务类', value: 1 },
  { label: '系统类', value: 2 },
  { label: '其他', value: 9 },
]

// Refs and reactive
const emits = defineEmits(['success'])
const editFormRef = ref<EditFormRef | null>(null)

const formDialog = reactive({
  top: '15vh',
  width: '1200px',
  type: 'add' as IFormDialogTypeProps,
  title: '新增',
  visible: false,
})

const searchFormData = ref({
  type: OPTIONS[0].value,
})

// API requests
const { refresh, run, data, loading } = useRequest(ConfigService.getTree, {
  manual: true,
})

// Methods
const show = (type: IFormDialogTypeProps, data: Partial<ConfigItem> = {}) => {
  formDialog.type = type
  if (type === 'view') {
    searchFormData.value = { type: data.type ?? OPTIONS[0].value }
    run(searchFormData.value)
    formDialog.title = '查看'
    formDialog.visible = true
  }
}

const tabChange = () => {
  run(searchFormData.value)
}

const add = (data: Partial<ConfigItem>, options: ConfigItem[] = []) => {
  editFormRef.value?.show(
    'add',
    {
      ...data,
    },
    options,
  )
}

const update = (data: ConfigItem, options: ConfigItem[] = []) => {
  editFormRef.value?.show('update', { ...data }, options)
}

const del = async (data: { id: number }) => {
  try {
    await ElMessageBox.confirm('删除当前数据, 是否继续?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
    await ConfigService.deleteObj(data.id)
    ElMessage.success('删除成功')
    refresh()
  } catch {
    ElMessage.info('已取消删除')
  }
}

const refreshTableData = () => {
  refresh()
  emits('success')
}

defineExpose({ show })
</script>

<template>
  <el-dialog
    :title="formDialog.title"
    v-model="formDialog.visible"
    :top="formDialog.top"
    :width="formDialog.width"
    :close-on-click-modal="false"
    :append-to-body="true"
    destroy-on-close
    class="body-padding-none"
  >
    <div class="border border-solid border-gray-300" :loading="loading">
      <LTab v-model="searchFormData.type" :options="OPTIONS" @change="tabChange">
        <template #top-right>
          <el-button size="small" type="primary" @click="add({}, data ?? [])"> 新增 </el-button>
        </template>
        <div class="p-2">
          <el-table :data="data" row-key="id" border>
            <el-table-column prop="title" label="名称" />
            <el-table-column prop="prop" label="KEY" />
            <el-table-column fixed="right" label="操作" width="120" align="center">
              <template #default="scope">
                <el-button
                  size="small"
                  icon="Edit"
                  type="warning"
                  title="编辑"
                  @click="update(scope.row, data ?? [])"
                />
                <el-button
                  size="small"
                  icon="Delete"
                  type="danger"
                  title="删除"
                  @click="del(scope.row)"
                />
              </template>
            </el-table-column>
          </el-table>
        </div>
      </LTab>
    </div>
  </el-dialog>

  <!-- 修改表单 -->
  <EditForm ref="editFormRef" @success="refreshTableData" />
</template>
